package com.atguigu.bigdata.gmall.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.bigdata.gmall.realtime.app.BaseAppV1;
import com.atguigu.bigdata.gmall.realtime.bean.TradeOrderWindow;
import com.atguigu.bigdata.gmall.realtime.bean.TradeOrderWindow;
import com.atguigu.bigdata.gmall.realtime.bean.TradeOrderWindow;
import com.atguigu.bigdata.gmall.realtime.common.Constant;
import com.atguigu.bigdata.gmall.realtime.util.AtguiguUtil;
import com.atguigu.bigdata.gmall.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.functions.RichFilterFunction;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.math.BigDecimal;
import java.time.Duration;
import java.util.HashSet;

public class Dws_02_DwsTradeOrderWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_02_DwsTradeOrderWindow().init(
                2005,
                2,
                "Dws_02_DwsTradeOrderWindow",
                Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1. 按照订单详情 id 去重: 取第一个详情. 没有用到 left join 的右表的数据
        SingleOutputStreamOperator<JSONObject> distinctedStream = distinctByOrderDetailId(stream);
        // 2. 解析成一个 pojo
        SingleOutputStreamOperator<TradeOrderWindow> beanStream = parseToPojo(distinctedStream);
        // 3. 开窗聚和
        SingleOutputStreamOperator<TradeOrderWindow> resultStream = windowAndAgg(beanStream);
        // 5. 写出到 clickhouse 中
        writeToClickHouse(resultStream);
    }

    private void writeToClickHouse(SingleOutputStreamOperator<TradeOrderWindow> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink("dws_trade_order_window",TradeOrderWindow.class));
    }

    private SingleOutputStreamOperator<TradeOrderWindow> windowAndAgg(
            SingleOutputStreamOperator<TradeOrderWindow> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<TradeOrderWindow>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean, ts) -> {
                                    // System.out.println("ts: " + ts);
                                    return bean.getTs();
                                })
                )
                .windowAll(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(5)))
                .reduce(
                        new ReduceFunction<TradeOrderWindow>() {
                            @Override
                            public TradeOrderWindow reduce(TradeOrderWindow value1,
                                                           TradeOrderWindow value2) throws Exception {
                                // 把 value2 中的order_id 都存入到 value1 中的 set 集合中
                                value1.getOrderIdSet().addAll(value2.getOrderIdSet());
                                value1.getUserIdSet().addAll(value2.getUserIdSet());
                                value1.setOrderAmount(value1.getOrderAmount().add(value2.getOrderAmount()));
                                return value1;
                            }
                        },
                        new ProcessAllWindowFunction<TradeOrderWindow, TradeOrderWindow, TimeWindow>() {
                            @Override
                            public void process(Context ctx,
                                                Iterable<TradeOrderWindow> elements,
                                                Collector<TradeOrderWindow> out) throws Exception {
                                TradeOrderWindow bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDatTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDatTime(ctx.window().getEnd()));

                                bean.setOrderCount((long) bean.getOrderIdSet().size());
                                bean.setOrderUserCount((long) bean.getUserIdSet().size());
                                bean.setTs(System.currentTimeMillis());

                                out.collect(bean);
                            }
                        }
                );


    }

    private SingleOutputStreamOperator<TradeOrderWindow> parseToPojo(
            SingleOutputStreamOperator<JSONObject> stream) {
        return stream
                .map(new MapFunction<JSONObject, TradeOrderWindow>() {
                    @Override
                    public TradeOrderWindow map(JSONObject value) throws Exception {
                        HashSet<String> orderIdSet = new HashSet<>();
                        orderIdSet.add(value.getString("order_id"));

                        HashSet<String> userIdSet = new HashSet<>();
                        userIdSet.add(value.getString("user_id"));

                        BigDecimal orderAmount = value.getBigDecimal("final_amount");
                        long ts = value.getLong("ts") * 1000;

                        return new TradeOrderWindow(
                                "", "",
                                orderIdSet, userIdSet, 0L, 0L, orderAmount,
                                ts
                        );
                    }
                });
    }

    private SingleOutputStreamOperator<JSONObject> distinctByOrderDetailId(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getString("id"))
                .filter(new RichFilterFunction<JSONObject>() {

                    private ValueState<Boolean> isFirstState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        ValueStateDescriptor<Boolean> desc = new ValueStateDescriptor<>("isFirstState", Boolean.class);
                        // 给状态设置 ttl
                        desc.enableTimeToLive(new StateTtlConfig.Builder(Time.seconds(10)).build());
                        isFirstState = getRuntimeContext().getState(desc);
                    }

                    @Override
                    public boolean filter(JSONObject value) throws Exception {
                        if (isFirstState.value() == null) {
                            isFirstState.update(false);
                            return true;
                        }

                        return false;
                    }
                });
    }
}
